package com.amumu.drama.common.modules.service.impl.payment.handler;

import cn.hutool.json.JSONUtil;
import com.amumu.drama.common.config.WXProperties;
import com.amumu.drama.common.constant.*;
import com.amumu.drama.common.exception.Asserts;
import com.amumu.drama.common.modules.order.dao.PortalOrderDao;
import com.amumu.drama.common.modules.order.dto.OmsOrderDetail;
import com.amumu.drama.common.modules.order.manager.OrderManager;
import com.amumu.drama.common.modules.service.impl.payment.PaymentFactory;
import com.amumu.drama.common.modules.service.impl.payment.PaymentReq;
import com.amumu.drama.common.modules.service.impl.payment.PaymentResp;
import com.amumu.drama.common.modules.sumapay.dto.req.AsyncResultReq;
import com.amumu.drama.common.modules.sumapay.dto.req.WeChatSingleOrderQueryReq;
import com.amumu.drama.common.modules.sumapay.dto.resp.WeChatPaySuccessResp;
import com.amumu.drama.common.modules.yipay.constat.YipayConstants;
import com.amumu.drama.common.modules.yipay.constat.YipayTypeEnum;
import com.amumu.drama.common.modules.yipay.dto.req.YipaySubmitReq;
import com.amumu.drama.common.modules.yipay.dto.resp.YipayOrderResp;
import com.amumu.drama.common.modules.yipay.service.YipayService;
import com.amumu.drama.model.OmsOrderItem;
import com.amumu.drama.model.UmsMember;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
@EnableConfigurationProperties(WXProperties.class)
public class YiPaymentHandler implements PaymentHandler {


    private WXProperties wxProperties;

    @Autowired
    private OrderManager orderManager;

    @Autowired
    private YipayService yipayService;

    @Autowired
    private PortalOrderDao portalOrderDao;


    @Override
    public String[] type() {
        return new String[]{
                PaymentFactory.getPayHandlerType(PayTypeEnum.WX_PAY, PayProviderEnum.ALI_PAY, SourceTypeEnum.UNKNOWN),
                PaymentFactory.getPayHandlerType(PayTypeEnum.WX_PAY, PayProviderEnum.ALI_PAY, SourceTypeEnum.APP),
                PaymentFactory.getPayHandlerType(PayTypeEnum.WX_PAY, PayProviderEnum.ALI_PAY, SourceTypeEnum.PC),
        };
    }

    @Override
    public PaymentResp pay(PaymentReq param) {

        OmsOrderDetail orderDetail = param.getOrderDetail();

        List<OmsOrderItem> orderItemList = orderDetail.getOrderItemList();
        OmsOrderItem omsOrderItem = orderItemList.get(0);
        UmsMember umsMember = param.getUmsMember();
        log.info("开始进行微信支付");
        PaymentResp paymentResp = new PaymentResp();
        try {
            YipaySubmitReq request = new YipaySubmitReq();
            request.setOut_trade_no(orderDetail.getOrderSn());
            request.setType(YipayTypeEnum.WXPAY.getDesc());
            request.setName(omsOrderItem.getProductName());
            request.setMoney(omsOrderItem.getProductPrice().toString());
            YipayOrderResp payResp = null;
            try {
                payResp = yipayService.createOrder(request);
            } catch (Exception e) {
                //更新订单状态为支付失败
                log.error("丰付支付生成订单微信支付失败", e);
                paymentResp.setPayStatusEnum(PayStatusEnum.FAIL);
                paymentResp.setPayRemark(e.getMessage());
            }
            log.info("payment result {}", JSONUtil.toJsonStr(payResp));

            paymentResp.setPayRemark(payResp.getMsg());
            paymentResp.setApplyTime(LocalDateTime.now());
            paymentResp.setPayUrl(payResp.getPayUrl());
            if (Objects.equals(payResp.getCode(), YipayConstants.RESULT_SUCCESS)) {
                paymentResp.setPayStatusEnum(PayStatusEnum.PAYING);

            } else {
                paymentResp.setPayStatusEnum(PayStatusEnum.FAIL);
                paymentResp.setPayRemark(payResp.getMsg());
            }
            return paymentResp;
        } catch (Exception e) {
            log.error("{} 丰付支付微信付款失败 error {}", param, e.getMessage());
            throw e;
        }
    }


    /**
     * 查询订单的支付状态
     *
     * @param orderDetail
     */
    @Override
    public PaymentResp queryPayStatus(OmsOrderDetail orderDetail) {
        PaymentResp resp = new PaymentResp();
        WeChatSingleOrderQueryReq request = new WeChatSingleOrderQueryReq();
        request.setRequestId(orderDetail.getOrderSn());
        request.setOriginalRequestId(orderDetail.getOrderSn());
        WeChatPaySuccessResp paySuccessResp = yipayService.singleQuery(request);
        if (resp != null && SumapayResultConstants.SUCCESS.equals(paySuccessResp.getResult())) {
            // 支付成功
            resp.setPayStatusEnum(PayStatusEnum.SUCCESS);
        } else {
            resp.setPayStatusEnum(PayStatusEnum.PAYING);
        }
        return resp;
    }

    /**
     * 支付回调通知
     *
     * @param params
     * @param body
     */
    @Override
    public PaymentResp payNotify(Map<String, String> params, String body) {
        PaymentResp paymentResp = new PaymentResp();
        paymentResp.setPayRemark("success");
        AsyncResultReq resultReq = JSONUtil.parse(params).toBean(AsyncResultReq.class);
        OmsOrderDetail orderDetail = portalOrderDao.getDetailByPayOrderSn(resultReq.getRequestId());
        if (orderDetail == null) {
            log.error("orderDetail {} not exist", resultReq.getRequestId());
            Asserts.fail("订单不存在");
        }
        if (!Objects.equals(orderDetail.getPayStatus(), PayStatusEnum.PAYING.getCode())) {
            log.error("order {} status {} invalid", orderDetail.getId(), orderDetail.getStatus());
            Asserts.fail("订单状态不正确,无法支付");
        }
        boolean payStatus = false;
        String errMsg = "取消支付";
        if (SumapayResultConstants.NOTICE_STATUS_SUCCESS.equals(resultReq.getStatus())) {
            // 支付成功

        } else {
            //支付失败
        }
        return paymentResp;
    }
}
